package com.demo.utils;


import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DbcpUtil {
    private static DataSource dataSource;
    private static Connection con;

    public DbcpUtil() {
    }

    public static Connection getConnection() {
        if (dataSource == null) {
            initDataSource();
        }
        try {
            con = dataSource.getConnection();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return con;

    }

    public static void initDataSource() {
        FileInputStream is = null;
        Properties p = new Properties();
        String driverClassName = null;
        String url = null;
        String username = null;
        String password = null;
        int initialSize = 0;
        int minIdle = 0;
        int maxIdle = 0;
        int maxWait = 0;
        int maxActive = 0;
        try {
            String path = DbcpUtil.class.getClass().getResource("/")
                    .getPath();
            is = new FileInputStream(path + "dbcp.properties");
            p.load(is);
            driverClassName = p.getProperty("driverClassName");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");

            initialSize = Integer.parseInt(p.getProperty("dataSource.initialSize"));
            minIdle = Integer.parseInt(p.getProperty("dataSource.minIdle"));
            maxIdle = Integer.parseInt(p.getProperty("dataSource.maxIdle"));
            maxWait = Integer.parseInt(p.getProperty("dataSource.maxWait"));
            maxActive = Integer.parseInt(p.getProperty("dataSource.maxActive"));
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setDriverClassName(driverClassName);
        ds.setUsername(username);
        ds.setPassword(password);

        ds.setInitialSize(initialSize); // 初始的连接数；
        ds.setMaxActive(maxActive);
        ds.setMinIdle(minIdle);
        ds.setMaxIdle(maxIdle);
        ds.setMaxWait(maxWait);
        ds.setRemoveAbandoned(true);
        ds.setRemoveAbandonedTimeout(2000);
        dataSource = ds;
    }
}
